package com.easycarebn.main.fragment;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.AvatarResponse;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.UserProfile;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.squareup.picasso.Picasso;
import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class FragmentAccountInfo extends Fragment {

	private View mView;
	private static FragmentAccountInfo fragment = null;
	private IResult callIResult;
	private static String mTitle;

	private TextView mTvFullName;
	private TextView mTvEmail;
	private TextView mTvLastUpdate;
	private ImageView mImgAvatar;
	private EditText mEdtFullName;
	private TextView mTvBirthday;
	private RadioGroup mRdgSex;
	private RadioGroup mRdgNoti;
	private EditText mEdtAddress;
	private EditText mEdtEmail;
	private EditText mPhone;

	private Calendar mCalBirthday;
	private ProgressBar laddingavata;

	public static FragmentAccountInfo newInstance(String title) {
		if (fragment == null)
			fragment = new FragmentAccountInfo();
		mTitle = title;
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IResult) {
			callIResult = (IResult) activity;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_thongtincanhan, null);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		callIResult.onDisplay(Utils.TASK_CHILD, "");
		Utils.setTitlePage(mView, mTitle);
		Utils.setOnTouchHideKeyboard(getActivity(), (ViewGroup) mView);
		//

		laddingavata = (ProgressBar) mView.findViewById(R.id.laddingavata);

		mTvFullName = (TextView) mView.findViewById(R.id.tv_full_name);
		mTvEmail = (TextView) mView.findViewById(R.id.tv_email);
		mTvLastUpdate = (TextView) mView.findViewById(R.id.tv_last_updated);
		mImgAvatar = (ImageView) mView.findViewById(R.id.img_avata);
		mEdtFullName = (EditText) mView.findViewById(R.id.edt_fullname);
		mTvBirthday = (TextView) mView.findViewById(R.id.tv_birthday);
		mRdgSex = (RadioGroup) mView.findViewById(R.id.rdg_sex);
		mEdtAddress = (EditText) mView.findViewById(R.id.edt_address);
		mEdtEmail = (EditText) mView.findViewById(R.id.edt_email);
		mPhone = (EditText) mView.findViewById(R.id.edt_phone);

		mRdgNoti = (RadioGroup) mView.findViewById(R.id.rdg_notifi);
		//
		Button btn = (Button) mView.findViewById(R.id.btnLulai);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				requestChangeInfo();
			}
		});

		mImgAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.pickFile(getActivity(), Utils.REQ_EDIT_AVATAR);

			}
		});

		TextView btnEditAvatar = (TextView) mView
				.findViewById(R.id.tv_edit_avatar);
		btnEditAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.pickFile(getActivity(), Utils.REQ_EDIT_AVATAR);
			}
		});
	}

	@Override
	public void onStart() {
		loadInfo();
		super.onStart();
	}

	private void loadInfo() {
		if (mCalBirthday == null) {
			mCalBirthday = Calendar.getInstance();
		}
		UserResponse user = Utils.getUserLogin(getActivity());
		if (user == null || user.getUser() == null) {
			return;
		}
		UserProfile profile = user.getUser();
		mTvFullName.setText(profile.getFullname());
		mEdtFullName.setText(profile.getFullname());
		mTvEmail.setText(profile.getEmail());
		mEdtEmail.setText(profile.getEmail());
		MainActivity.mLoadingData.setVisibility(View.VISIBLE);
		Picasso.with(getActivity()).load(profile.getAvatarThumb())
				.resize(Utils.IMG_WIDHT, Utils.IMG_HEIGHT)
				.placeholder(R.drawable.avata).error(R.drawable.avata)
				.into(mImgAvatar);

		ServerController.getInstance(getActivity()).requestProfileLoadInfo(
				user.getToken(), new OnRequest<UserProfile>() {

					@Override
					public void onSuccess(final UserProfile data) {
						MainActivity.mLoadingData.setVisibility(View.GONE);
						if (data == null) {
							return;
						}
						Date date = Utils.convertDate(data.getBirthDate(),
								"yyyy-MM-dd");
						mCalBirthday.setTime(date);
						mTvBirthday.setText(mCalBirthday
								.get(Calendar.DAY_OF_MONTH)
								+ "-"
								+ (1 + mCalBirthday.get(Calendar.MONTH))
								+ "-"
								+ mCalBirthday.get(Calendar.YEAR));
						mTvBirthday.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								new DatePickerDialog(getActivity(),
										new OnDateSetListener() {

											@Override
											public void onDateSet(
													DatePicker view, int year,
													int monthOfYear,
													int dayOfMonth) {
												mCalBirthday.set(Calendar.YEAR,
														year);
												mCalBirthday.set(
														Calendar.MONTH,
														monthOfYear);
												mCalBirthday.set(
														Calendar.DAY_OF_MONTH,
														dayOfMonth);
												mTvBirthday.setText(dayOfMonth
														+ "/"
														+ (1 + monthOfYear)
														+ "/" + year);
											}
										}, mCalBirthday.get(Calendar.YEAR),
										mCalBirthday.get(Calendar.MONTH),
										mCalBirthday.get(Calendar.DAY_OF_MONTH))
										.show();
							}
						});
						if (data.getLastLogin() != null
								&& data.getLastLogin().getDate() != null) {
							Date date2 = Utils.convertDate(data.getLastLogin()
									.getDate(), "yyyy-MM-dd hh:mm:ss");
							mTvLastUpdate.setText(getString(
									R.string.lan_dang_nhap_cuoi_ps, DateFormat
											.format("hh:mm dd/MM/yyyy", date2)));
						}
						int rdSexId = (data.getGender() == 1) ? R.id.rd_male
								: R.id.rd_female;
						mRdgSex.check(rdSexId);
						mEdtAddress.setText(data.getAddress());
						if (!data.getPhone().isEmpty()) {
							mPhone.setEnabled(false);
							mPhone.setText(data.getPhone());
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						MainActivity.mLoadingData.setVisibility(View.GONE);
						// Utils.showMessage(getActivity(), message);
					}
				});
	}

	private void requestChangeInfo() {
		final UserResponse user = Utils.getUserLogin(getActivity());
		if (user == null) {
			Utils.showMessage(getActivity(), R.string.ban_chua_dang_nhap);
			return;
		}
		String token = user.getToken();
		final String fullname = mEdtFullName.getText().toString();
		final String phone = mPhone.getText().toString();
		if (phone.length() > 11 || phone.length() < 10) {
			Utils.showMessage(getActivity(), R.string.so_dien_thoai_ko_hop_le);
			return;
		}

		final String email = mEdtEmail.getText().toString();
		String birthdate = mCalBirthday.get(Calendar.YEAR) + "-"
				+ (1 + mCalBirthday.get(Calendar.MONTH)) + "-"
				+ mCalBirthday.get(Calendar.DAY_OF_MONTH);
		int gender = (mRdgSex.getCheckedRadioButtonId() == R.id.rd_male) ? 1
				: 0;
		String address = mEdtAddress.getText().toString();
		boolean emailnoti = (mRdgNoti.getCheckedRadioButtonId() == R.id.rd_email) ? true
				: false;
		MainActivity.mLoadingData.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);

		ServerController.getInstance(getActivity())
				.requestProfileChangeProfile(token, fullname, email, birthdate,
						gender, address, emailnoti, phone,
						new OnRequest<DataItemResponse>() {

							@Override
							public void onSuccess(DataItemResponse data) {
								MainActivity.mLoadingData
										.setVisibility(View.GONE);
								Utils.disableEnableControls(true, mView);
								// Update UI
								mTvFullName.setText(fullname);
								mTvEmail.setText(email);
								user.getUser().updateEmail(email);
								user.getUser().updateFullname(fullname);
								Utils.updateUserLogin(getActivity(), user);
								// Update right menu
								Activity activity = getActivity();
								if (activity instanceof MainActivity) {
									((MainActivity) activity).showAccInfo(user);
								}
								Utils.showMessage(getActivity(),
										R.string.thay_doi_thong_tin_thanh_cong);
							}

							@Override
							public void onError(int errorCode, String message) {
								MainActivity.mLoadingData
										.setVisibility(View.GONE);
								Utils.disableEnableControls(true, mView);

								Utils.showMessage(getActivity(), message);
							}
						});
	}

	public void updateInfo(Intent data) {
		final UserResponse user = Utils.getUserLogin(getActivity());
		if (user == null) {
			Utils.showMessage(getActivity(), R.string.ban_chua_dang_nhap);
			return;
		}
		String token = user.getToken();
		Uri selectedImage = data.getData();
		// mImgAvatar.setImageURI(selectedImage);
		File file = new File(Utils.getRealPathFromURI(getActivity(),
				selectedImage));
		laddingavata.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestUploadAvatar(token,
				file, new OnRequest<AvatarResponse>() {

					@Override
					public void onSuccess(AvatarResponse data) {
						laddingavata.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(),
								R.string.cap_nhat_anh_dai_dien_thanh_cong);
						user.getUser().updateAvatar(data.getNewAvatar());
						Picasso.with(getActivity()).load(data.getNewAvatar())
								.resize(Utils.IMG_WIDHT, Utils.IMG_HEIGHT)
								.placeholder(R.drawable.avata)
								.error(R.drawable.avata).into(mImgAvatar);
						// Update right menu
						Activity activity = getActivity();
						if (activity instanceof MainActivity) {
							((MainActivity) activity).showAccInfo(user);
						}
						Utils.updateUserLogin(getActivity(), user);
					}

					@Override
					public void onError(int errorCode, String message) {
						laddingavata.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), message);
					}
				});
	}
}
